﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using CWCS.UIDesigner.DTSControl;
using CWCS.Common;
using CWCS.Common.Log;
using CWCS.BLL.WebsocketCommon;

namespace CWCS.BLL
{
    public class BLLDTS : BLLBase
    {
        //public delegate void DTSNotifyMessage(string Command, object Mesg);
        public delegate void DTSNotifyMessage(string Command, DTSControl dTSControl, object Mesg);
        public event DTSNotifyMessage ShowDTSMsg;
        DTSControl DTSClient;
        LogHelper logDTS  = new LogHelper("DTS");
        public string strIP;
        Timer CheckTimer;
        Timer ConnectTimer;
        private string FaceCode = System.Configuration.ConfigurationSettings.AppSettings["FaceCode"].ToString();

        public Timer CheckConnectTimer
        {
            get
            {
                if (CheckTimer == null)
                {
                    CheckTimer = new Timer();
                }
                return CheckTimer;
            }
        }
        public Timer AutoConnectTimer
        {
            get
            {
                if (ConnectTimer == null)
                {
                    ConnectTimer = new Timer();
                }
                return ConnectTimer;
            }
        }

        public bool InitServer(string sIP, int sPort)
        {
            try
            {
                this.strIP = sIP;
                DTSClient = new DTSControl(sIP, sPort);
                DTSClient.EAnlyseData += new DTSControl.AnalyseMessageEventHandler(RecMsg);
                RecMsg(NotifyCommand.Linking, "DTS连接中..."+ sIP);
                bool flag = DTSClient.Connection();
                CheckConnectTimer.Interval = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["CheckDTSConnect"]);
                CheckConnectTimer.Elapsed += new ElapsedEventHandler(CheckConnectTimer_Elapsed);//若连接失败则检测网络直到连接上了


                AutoConnectTimer.Interval = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["AutoDTSConnect"]);
                AutoConnectTimer.Elapsed += new ElapsedEventHandler(AutoConnectTimer_Elapsed);

                if (flag)
                {
                    RecMsg(NotifyCommand.Connect, "DTS连接成功!" + sIP);
                    CheckConnectTimer.Start();
                }
                else
                {
                    RecMsg(NotifyCommand.Break, "DTS连接失败!" + sIP);
                    AutoConnectTimer.Start();
                }

            }
            catch (Exception ex)
            {
                ShowDTSLog("Break", DTSClient, "WCS初始化DTS异常：" + ex.Message);
            }
            return false;
        }

        private void DTSNotify_Message(string Command, object Mesg)
        {
            switch (Command)
            {
                case "Break": ShowDTSLog(Command, DTSClient, Mesg); break;
                case "Listen":
                    ShowDTSLog(Command, DTSClient, Mesg); break;
                case "RecvData":
                    ShowDTSLog(Command, DTSClient, Mesg);
                    DoProcess(Mesg); break;
            }
        }

        private void RecMsg(NotifyCommand command, object Msg)
        {
            if (ShowDTSMsg != null)
            {
                switch (command)
                {
                    case NotifyCommand.Connect: ShowDTSLog("Connect", DTSClient, Msg); break;
                    case NotifyCommand.Linking: ShowDTSLog("Linking", DTSClient, Msg); break;
                    case NotifyCommand.Break: ShowDTSLog("Break", DTSClient, Msg); break;
                    case NotifyCommand.RecvData:
                        ShowDTSLog("RecvData", DTSClient, "DTS->WCS，信息如下：" + Msg + "\r");
                        DoProcess(Msg);
                        break;
                }
            }
        }

        private bool DoProcess(object RecData)
        {
            if (!string.IsNullOrEmpty(RecData.ToString()))
            {
                if (CheckLocationState(RecData.ToString().Substring(0, 11)) > 0)
                {
                    ShowDTSLog("WCS->WMS", DTSClient, "WCS收到货位:" + RecData.ToString() + "后更新OutFlag标识成功！");
                    return true;
                }
                else
                {
                    ShowDTSLog("WCS->WMS", DTSClient, "WCS收到货位:" + RecData.ToString() + "后更新OutFlag标识失败!");
                    return false;
                }
            }
            return false;
        }

        private void CheckConnectTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            string sss = "DTS|" + DateTime.Now.ToString();
            if (!DTSClient.Send(sss, 1))
            {
                AutoConnectTimer.Start();
                CheckConnectTimer.Stop();
            }
        }
        private void AutoConnectTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (DTSClient.Connection())
            {
                AutoConnectTimer.Stop();
                CheckConnectTimer.Start();
            }
            else
            {
                DTSClient.DisConnect();
            }
        }

        /// <summary>
        /// 日志显示
        /// </summary>
        /// <param name="type"></param>
        /// <param name="msg"></param>
        public void ShowDTSLog(string type, DTSControl dTSControl, object msg)
        {
            if (!string.IsNullOrEmpty(msg.ToString()) && msg.ToString().Length > 7)//判断长度是否大于7，否则直接记录日志（避免报异常）
            {
                if (ShowDTSMsg != null)
                {
                    ShowDTSMsg(type, dTSControl, msg);
                    logDTS.Info(msg.ToString());
                    string[] dtsInfo =  new string[2];
                    dtsInfo[0] = type;
                    dtsInfo[1] = msg.ToString();
                    var dtsMsgString = Newtonsoft.Json.JsonConvert.SerializeObject(dtsInfo);
                    WebSocketHelper.SendMsgToRemotePoint("DtsMsg" + dtsMsgString);
                }
            }
        }
    }
}
